package com.pussinboots.morning.sync.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pussinboots.morning.sync.dao.BuffProductMapper;
import com.pussinboots.morning.sync.dao.ProductAttributeMapper;
import com.pussinboots.morning.sync.entity.BuffProduct;
import com.pussinboots.morning.sync.entity.Product;
import com.pussinboots.morning.sync.entity.ProductAttribute;
import com.pussinboots.morning.sync.eu.SyncEnum;
import com.pussinboots.morning.sync.service.*;
import lombok.extern.apachecommons.CommonsLog;
import lombok.val;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
@CommonsLog
public class BuffProductService extends ServiceImpl<BuffProductMapper, BuffProduct> implements IBuffProductService {
    @Autowired
    private IProductService productService;
    @Autowired
    private IProductAttributeService attributeService;
    @Autowired
    ProductAttributeMapper productAttributeMapper;
    @Autowired
    private IProductAreaService productAreaService;
    @Autowired
    private IProductCategoryService productCategoryService;

    @Override
    @Transactional
    public Boolean sync() {
        dataSync(SyncEnum.ADD);
        dataSync(SyncEnum.UPDATE);
        dataSync(SyncEnum.DEL);
        return null;
    }

    private Boolean dataSync(SyncEnum syncTypeEnum) {
        val buffProductList = this.list(new QueryWrapper<BuffProduct>().eq(syncTypeEnum.getSyncTag(), syncTypeEnum.getTagVal()).last("limit 100"));
        if (buffProductList.isEmpty()) {
            return false;
        }

        val productList = new ArrayList<Product>();
        val productIdList = new ArrayList<Long>();
        Product product;

        for (BuffProduct buffPro : buffProductList) {
            // 价格不符合标准时，统一处理成999，便于查找
            if (buffPro.getShowPrice() == null || buffPro.getShowPrice().compareTo(BigDecimal.ZERO) == 0) {
                buffPro.setShowPrice(new BigDecimal(999));
            }
            product = Product.builder().status(1)/*.productId(buffPro.getMorningKey())*/.build();
            // 商品中间表复制属性给到商品表
            BeanUtils.copyProperties(buffPro, product);
            productList.add(product);
            productIdList.add(buffPro.getMorningKey());
        }
        // 批量操作商品表
        boolean batchOptResult = false;
        switch (syncTypeEnum) {
            case ADD:
                batchOptResult = productService.saveBatch(productList);
                List<Long> productIds = getProductIds(productList);
                productCategoryService.saveDefaultProductCategory(productList);
                productAreaService.add1ProductTo32provinceRltn(productIds);
                break;
            case UPDATE:
                batchOptResult = productService.updateBatchById(productList);
                productAreaService.update1ProductTo32provinceRltn(productIdList);
                break;
            case DEL:
                batchOptResult = productService.removeByIds(productIdList);
                productCategoryService.delProductCategory(productIdList);
                productAreaService.remove1ProductTo32provinceRltn(productIdList);
                break;
            default: break;
        }
        if (!batchOptResult) {
            // TODO 加入日志（中间表写入产品表失败）
            return batchOptResult;
        }
        val attrList = new ArrayList<ProductAttribute>();
        val returnBuffProList = new ArrayList<BuffProduct>();
        ProductAttribute productAttribute = null;
        BuffProduct returnBuffPro;
        for (Product pro : productList) {
            productAttribute = ProductAttribute.builder()
                    /*.productId(pro.getProductId())*/.stock(pro.getStock()).build();
            attrList.add(productAttribute);

            returnBuffPro = BuffProduct.builder()
                    //.id(pro.getId())
                    /*.morningKey(pro.getProductId())*/.addTag(0).updateBy("morning").build();
            switch (syncTypeEnum) {
                case ADD: returnBuffPro.setAddTag(0).setUpdateTag(null).setDelTag(null); break;
                case UPDATE: returnBuffPro.setUpdateTag(0).setAddTag(null).setDelTag(null); break;
                case DEL: returnBuffPro.setDelTag(0).setAddTag(null).setUpdateTag(null); break;
                default: break;
            }
            returnBuffProList.add(returnBuffPro);
        }

        boolean returnBuffResult = false;
        switch (syncTypeEnum) {
            case ADD:
                batchOptResult = attributeService.saveBatch(attrList);
                returnBuffResult = this.updateBatchById(returnBuffProList);
                break;
            case UPDATE:
                //batchOptResult = productAttributeMapper.updateBatchByProductId(attrList);
                returnBuffResult = this.updateBatchById(returnBuffProList);
                break;
            case DEL:
                batchOptResult = productAttributeMapper.removeBatchByProductId(productIdList);
                returnBuffResult = this.updateBatchById(returnBuffProList);
                break;
            default: break;
        }

        // 批量插入商品属性表（主要是库存）
        if (!batchOptResult) {
            // TODO 加入日志（新增库存失败）
            return batchOptResult;
        }

        if (!returnBuffResult) {
            // TODO 加入日志（回传状态失败）
            return returnBuffResult;
        }
        return false;
    }

    private List<Long> getProductIds(List<Product> proList) {
        val productIdList = new ArrayList<Long>();
        for (Product product : proList) {
            //productIdList.add(product.getId());
        }
        return productIdList;
    }
}
